/**
 * Created by henian.xu on 2016/12/29.
 *
 */

/*var
  $ = require('jquery'),
  WebUploader = require('webuploader'),
  dialog = require('artdialogWrap'),
  ctx = window.ctx || window.global.ctx || '';*/

var Webuploader = (function () {
  //构造函数
  function Main(options) {
    //类属性初始化
    this.opt = $.extend(true, {}, this.defaults, options);
    this.fileArr = [];
    this._maxNum = this.opt.webuploader.fileNumLimit;//最大上传数量
    this.uploader = null;

    if (this.opt.containerEl === null) {
      console.error('上传控件容器 = null');
      return;
    } else {
      //缓存一些主要dom
      this.opt.$containerEl = $(this.opt.containerEl);
      this.opt.$uploadBtn = this.opt.$containerEl.find('.wup-uploadBtn');
      this.opt.$fileArrInput = this.opt.$containerEl.find('.wup-fileArr');
    }
    if (typeof this.opt.webuploader.pick === 'string') {
      this.opt.webuploader.$pick = this.opt.$containerEl.find(this.opt.webuploader.pick);
      if (this.opt.webuploader.$pick.length) {
        this.opt.webuploader.pick = this.opt.webuploader.$pick.get(0);
      } else {
        this.opt.webuploader.pick = null;
      }

    }

    this._init();
    this._initFileArr();
    this._bindEvent();
  }

  //初始化
  Main.prototype._init = function () {
    var self = this;
    //如果没有点击按钮，无需创建 WebUploader 实例
    this.opt.webuploader.pick = {
      id: this.opt.webuploader.pick,
      multiple: false
      //TODO 暂时不支持多选
    };
    this.uploader = this.opt.webuploader.pick && WebUploader.create(this.opt.webuploader);
    this.opt.$containerEl.data('z-webuploader', this);
  };
  //插入初始值
  Main.prototype._initFileArr = function () {
    var
      fileName = this.opt.$fileArrInput.val(),
      fileAddress = this.opt.$fileArrInput.data('address');
    if (!fileName) {
      this.opt.$uploadBtn.show();
      $(window).trigger('resize');
      return;
    }
    var
      fileNameArr = fileName.split(','),
      fileAddressArr = fileAddress.split(',');

    if (!fileNameArr[fileNameArr.length - 1]) {
      fileNameArr.splice(fileNameArr.length - 1, 1);
    }

    if (!fileAddressArr[fileAddressArr.length - 1]) {
      fileAddressArr.splice(fileAddressArr.length - 1, 1);
    }

    if (fileNameArr.length !== fileAddressArr.length) {
      console.error('附件长度不一样');
    }

    for (var i = 0; i < fileNameArr.length; i++) {
      var
        name = fileNameArr[i],
        address = fileAddressArr[i];
      this.fileArr.push({
        name: name,
        address: address
      });
    }

    this._isExceed();//判断初始是否已达到上传上限
    console.log(this.fileArr);

  };
  //事件绑定
  Main.prototype._bindEvent = function () {
    var self = this;
    // 如果没有创建 WebUploader 实例，无需绑定相关事件
    if (self.uploader) {
      // 开始上传事件
      self.uploader.on('uploadStart', function () {
        self._onUploadStart.apply(self, arguments);
      });
      // 上传进度事件
      self.uploader.on('uploadProgress', function () {
        self._onUploadProgress.apply(self, arguments);
      });
      // 上传成功事件
      self.uploader.on('uploadSuccess', function () {
        self._onUploadSuccess.apply(self, arguments);
      });
      // 上传失败事件
      self.uploader.on('uploadError', function () {
        self._onUploadError.apply(self, arguments);
      });
      // 上传完毕，重置队列
      self.uploader.on('uploadFinished', function () {
        self._onUploadFinished.apply(self, arguments);
      });
      // 上传失败事件
      self.uploader.on('error', function (handle) {
        self._onError.apply(self, arguments);
      });
    }
    //放大按钮事件
    $(this.opt.containerEl).on('click', '.wup-ctrl>.wup-zoom', function () {
      var option = [self].concat(arguments);
      Main.prototype._onZoomClick.apply(this, option);
    });
    //删除按钮事件
    $(this.opt.containerEl).on('click', '.wup-ctrl>.wup-del', function () {
      var option = [self].concat(arguments);
      Main.prototype._onDelClick.apply(this, option);
    });

  };
  // 开始上传事件
  Main.prototype._onUploadStart = function (file) {
    var $node = $('<li class="wup-fileItem">' +
        '<img src=""><div class="wup-progress"><div class="inner"></div></div>' +
        '<div class="wup-ctrl">' +
        '<di class="wup-del" data-name=""><i class="z-icon z-icon-f00d"></i></di>' +
        '<di class="wup-zoom" data-zoomsrc=""><i class="z-icon z-icon-f002"></i></di>' +
        '</div>' +
        '</li>'),
      $progress = $node.find('.wup-progress');
    file.$node = $node;
    $node.data('file', file);
    console.log(file);
    $node.insertBefore(this.opt.$uploadBtn);
    this._isExceed();
  };
  // 上传进度事件
  Main.prototype._onUploadProgress = function (file, percentage) {
    var $node = file.$node,
      $progressInner = $node.find('.wup-progress>.inner');
    $progressInner.width(percentage * 100 + '%');
  };
  // 上传成功事件
  Main.prototype._onUploadSuccess = function (file, res) {
    if (!res.success) {
      alert(res.msg);
      return;
    }
    this.fileArr.push(res.data);
    this.opt.onFilesChang.call(this, this.fileArr.length);
    this._isExceed();//这里其实可以不判断了，因为在开始上传时 判断过了
    this._upDataFileValue();

    //console.log(file,res);
    var $node = file.$node,
      $img = $node.find('img'),
      $del = $node.find('.wup-del'),
      $zoom = $node.find('.wup-zoom'),
      $progress = $node.find('.wup-progress');

    file.complete = true;//点击删除时用来判断是否正在上传
    $img[0].src = res.data.address;
    $del.data('name', res.data.name);
    $zoom.data('zoomsrc', res.data.address);
    $progress.hide();

    // this._renderList();

  };
  // 更新 fileValue
  Main.prototype._upDataFileValue = function () {
    //value赋值
    /*var fileValue = this.opt.$fileArrInput.val(),
     fileValueArr = !!fileValue ? fileValue.split',') : [];
     fileValueArr.push(res.data.name);
     this.opt.$fileArrInput.val(fileValueArr.join(','));*/
    var names = [];
    $.each(this.fileArr, function (i, t) {
      names.push(t.name);
    });
    this.opt.$fileArrInput.val(names.join(','));
  };
  //判断是否超过最大限制上传数量
  Main.prototype._isExceed = function () {
    var stats = this.uploader.getStats();
    if (!this.opt.$uploadBtn.length) {
      this.opt.$uploadBtn = this.opt.$containerEl.find('.wup-uploadBtn');
    }
    if (this._maxNum && this.fileArr.length + stats.queueNum >= this._maxNum) {
      // !!this.uploader && this.uploader.disable();
      this.opt.$uploadBtn.hide();
    } else {
      // !!this.uploader && this.uploader.enable();
      this.opt.$uploadBtn.show();
      $(window).trigger('resize');
    }
  };
  // 上传失败事件
  Main.prototype._onUploadError = function (file, reason) {
    var $node = file.$node;
    $node.remove();
    this._isExceed();
    alert(reason);
  };
  // 上传完毕，重置队列
  Main.prototype._onUploadFinished = function (e) {
    this.uploader.reset();
  };
  // 上传失败事件
  Main.prototype._onError = function (handle) {
    alert(handle);
  };
  //渲染列表
  Main.prototype._renderList = function () {
    var
      selt = this,
      liArr = [],
      names = [];
    $.each(this.fileArr, function (i, t) {
      liArr.push('<li class="wup-fileItem">' +
        '<img src="' +
        t.address +
        '">' +
        // '<div class="wup-progress"><div class="inner"></div></div>' +
        '<div class="wup-ctrl">' +
        '<di class="wup-del" data-name="' +
        t.name +
        '"><i class="z-icon z-icon-f00d"></i></di>' +
        '<di class="wup-zoom" data-zoomsrc="' +
        t.address +
        '"><i class="z-icon z-icon-f002"></i></di>' +
        '</div>' +
        '</li>');
      names.push(t.name);
    });
    if (this.fileArr.length) {
      this.opt.$fileArrInput.siblings('.error').remove();
    }
    this.opt.$containerEl.find('.wup-fileItem:not(.wup-uploadBtn)').remove();
    this.opt.$containerEl.prepend(liArr.join(' '));
    this.opt.$fileArrInput.val(names.join(','));
  };

  //删除按钮事件
  Main.prototype._onDelClick = function (self) {
    var
      $this = $(this),
      $wupFileItem = $this.closest('.wup-fileItem'),
      file = $wupFileItem.data('file'),
      name = $this.data('name');

    //如果是正在传的 从列队中删除
    if (!!file && !file.complete) {
      self.uploader.removeFile(file);
    }

    $.each(self.fileArr, function (i, t) {
      if (t.name == name) {
        self.fileArr.splice(i, 1);
        this.opt.onFilesChang.call(this, this.fileArr.length);
        return false;
      }
    });
    self._isExceed();
    self._upDataFileValue();
    $wupFileItem.remove();
    // self._renderList();
  };

  // 放大按钮事件
  Main.prototype._onZoomClick = function () {
    var
      $this = $(this),
      $node = $('<div class="z-popup-img"><img src="' +
        $this.data('zoomsrc') +
        '" alt=""></div>'),
      $wrap = $('.z-components');
    if (!$wrap.length) {
      $wrap = $(document.body);
    }
    $node.one('click', function () {
      $(this).remove();
    });
    $wrap.append($node);
  };
  //默认参数
  Main.prototype.defaults = {

    containerEl: null,//上传控件容器 必选
    onFilesChang: function () {
    },
    webuploader: {
      pick: '.wup-filePicker',
      auto: true,
      duplicate: true,
      fileVal: "file",
      fileNumLimit: 5,//最大上传数量
      fileSingleSizeLimit: 4 * 1024 * 1024,

      server: '',
      accept: {
        title: 'Images',
        extensions: 'gif,jpg,jpeg,bmp,png',
        mimeTypes: 'image/*'
      },
      swf: '../lib/webuploader.swf'
    }
  };

  return Main;
})();

// module.exports = CLASS;


